package medicalDocumentation.medicalRepository;

import entity.MedicalKnowledge;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class MedicalKnowledgeRepositorySessionBean implements MedicalKnowledgeRepositorySessionBeanRemote {
 public final String MEDICAL_KNOWLEDGE_CONDITION_REQUIRED = "Medical knowledge condition required";
    @PersistenceContext
    private EntityManager entityManager;
    
    @Override
    public String addMedicalKnowledge(String medicalKnowledgeCondition, String medicalKnowledgeInformation, String remark) {
        if (medicalKnowledgeCondition == null) {
            return MEDICAL_KNOWLEDGE_CONDITION_REQUIRED;
        }
        MedicalKnowledge medicalKnowledge = new MedicalKnowledge();
        medicalKnowledge.setMedicalKnowledgeCondition(medicalKnowledgeCondition);
        medicalKnowledge.setMedicalKnowledgeInformation(medicalKnowledgeInformation);
        medicalKnowledge.setRemark(remark);
        entityManager.persist(medicalKnowledge);
        entityManager.flush();
        return String.valueOf(medicalKnowledge.getId());
    }

    @Override
    public List<MedicalKnowledge> getMedicalKnowledgeById(String id) {
        String strQuery = "SELECT m FROM MedicalKnowledge m WHERE m.id = :inId";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inId", Long.valueOf(id));
        return query.getResultList();
    }

    @Override
    public List<MedicalKnowledge> getAllMedicalKnowledge() {
        String strQuery = "SELECT m FROM MedicalKnowledge m";
        Query query = entityManager.createQuery(strQuery);
        return query.getResultList();
    }

    @Override
    public void deleteMedicalKnowledge(String id) {
        List medicalKnowledges = getMedicalKnowledgeById(id);
        if (medicalKnowledges.get(0) != null) {
            entityManager.remove(medicalKnowledges.get(0));
            entityManager.flush();
        }
    }

    @Override
    public void updateMedicalKnowledge(String id, String medicalKnowledgeCondition, String medicalKnowledgeInformation, String remark) {
        MedicalKnowledge medicalKnowledge = getMedicalKnowledgeById(id).get(0);
        if (medicalKnowledge != null) {
            medicalKnowledge.setMedicalKnowledgeCondition(medicalKnowledgeCondition);
            medicalKnowledge.setMedicalKnowledgeInformation(medicalKnowledgeInformation);
            medicalKnowledge.setRemark(remark);
            entityManager.merge(medicalKnowledge);
            entityManager.flush();
        }
    }

}
